var TomcatUrl = JSON.parse(localStorage.getItem('$user')).TomcatUrl;
(function ($) {
	var uploadMethod = '/Fileupdate/servlet/VueFileuploadServlet?filesname=images/'
	var deleteMethod = '/Fileupdate/servlet/DeleteFileServlet?filename='
	var uploadServerURL=TomcatUrl+uploadMethod;
	var deleteServerURL=TomcatUrl+deleteMethod;
	mui.UploadFileToServer=function(fileArr,path,resultBlock){
		if (!fileArr || fileArr.length == 0) {
			resultBlock([])
			return
		}
		// FormData 对象
		var form = new FormData();
		// var fileNameStr = {};
		for (var i = 0; i < fileArr.length; i++) {
			var tempImageName = fileArr[i].name
			var tempArr = tempImageName.split('_')
			tempImageName = tempArr.join('-')
			var tempArr = tempImageName.split('|')
			tempImageName = tempArr.join('-')
			form.append("file", fileArr[i], tempImageName);
		}
		var xhr = null;
		if (window.XMLHttpRequest) {
			xhr = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}
		/*判断是否支持请求*/
		if (xhr == null) {
			mui.toast('你的浏览器不支持XMLHttp');
			return;
		}
		xhr.responseType = 'multipart/form-data';
		xhr.timeout = 12000;
		//为请求添加返回处理函数
		xhr.onreadystatechange = function() {
			if (this.readyState === 4 && this.status === 200) {
				var result = this.responseText.split(':')[0];
				var resultDesc = this.responseText.split(':')[1];
				if (result == 'success') {
					var succeedArr = resultDesc.split('^');
					mui.toast('上传成功' + succeedArr.length + '个');
					resultBlock(succeedArr);
				} else {
					mui.toast(this.responseText);
					resultBlock();
				}
			} else {
				// plus.nativeUI.closeWaiting();
				// mui.toast('上传失败!');
				// console.info('上传失败：' + this.readyState);
			}
		};
		xhr.onerror = function(e) {
			plus.nativeUI.closeWaiting();
			mui.toast('上传响应错误');
			resultBlock();
		}
		xhr.onabort = function(e) {
			plus.nativeUI.closeWaiting();
			mui.toast('上传响应中断');
			resultBlock();
		}
		xhr.ontimeout = function(e) {
			plus.nativeUI.closeWaiting();
			mui.toast('上传响应超时');
			resultBlock();
		}
		xhr.open("post", uploadServerURL+path, true);
		xhr.send(form);
	}
	mui.DeleteFileFromServer = function(shortPath,resultBlock){
		if (shortPath == '') {
			resultBlock(true)
			return
		}
		var xhr = null;
		if (window.XMLHttpRequest) {
			xhr = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}
		/*判断是否支持请求*/
		if (xhr == null) {
			mui.toast('你的浏览器不支持XMLHttp');
			return;
		}
		xhr.timeout = 8000;
		//为请求添加返回处理函数
		xhr.onreadystatechange = function() {
			if (this.readyState === 4 && this.status === 200) {
				var result = this.responseText.split(':')[0];
				var resultDesc = this.responseText.split(':')[1];
				if (result == 'success') {
					mui.toast('删除成功');
					resultBlock(true); 
				} else {
					if(resultDesc == '文件不存在'){
						resultBlock(true);
					}else{
						mui.toast(resultDesc);
						resultBlock(false);
					};
				}
			} else {}
		};
		xhr.onerror = function(e) {
			plus.nativeUI.closeWaiting();
			mui.toast('删除错误');
			resultBlock(false);
		}
		xhr.onabort = function(e) {
			plus.nativeUI.closeWaiting();
			mui.toast('删除中断');
			resultBlock(false);
		}
		xhr.ontimeout = function(e) {
			plus.nativeUI.closeWaiting();
			mui.toast('删除超时');
			resultBlock(false);
		}
		xhr.open("post", deleteServerURL+shortPath, true);
		xhr.send();
	}
})(mui)
function fileDomTapped(){
	var classStr = event.target.getAttribute('class')
	var url = this.getAttribute('data-url');
	var label = this.querySelector('.itemText').innerText
	var fileType = fileTypeIcon(label)
	if (fileType == 'img') {
		if (classStr&&classStr.indexOf('itemText') != -1) {
			mui.trigger(this.querySelector('img'),'tap')
		}
		return
	}
	var pageName = ''
	switch (fileType){
		case "pdf":
		case "word":
		case "ppt":
			//url='https://114.242.246.235:1443/imedical/web/scripts/nurse/nurtv/imedical+8.5升级开发需关注的相关要求.pdf'
			pageName = '../../FilePreview/pdfReader.html'
			break;
		default:
			break;
	}
	if (pageName == '') {
		mui.toast('暂不支持此类型文件')
		return
	}
	var webview = plus.webview.create(pageName, pageName, {
		background: '#fff',
		statusbar: {
			background: '#fff'
		}
	},{'title':label,'fileUrl':url});
	webview.show('fade-in');
}
//添加附件
function afterSelectFile(ulDomId,imageArr,files){
	var fileUL = $('#'+ulDomId)[0]
	for (var i = 0; i < files.length; i++) {
		var URL = window.URL || window.webkitURL;
		var currFile = files[i]
		var imgURL = URL.createObjectURL(currFile);
		var li = document.createElement('li');
		li.classList.add('mui-table-view-cell')
		li.id = ulDomId + '-' + imageArr.length
		
		var name = currFile['name']
		var icon = fileTypeIcon(name);
		var fileStr = ''
		if (icon == 'img') {
			icon = imgURL +'" data-preview-group="1" data-preview-src="'
		}else{
			icon = '../../dependence/teach/images/'+icon+'.svg'
		}
		fileStr = '<div class="itemImg"><img src="'+icon+'"/></div><div class="mui-ellipsis itemText">'+name+'</div>'
		li.innerHTML =  '<div class="mui-slider-right mui-disabled"><a class="mui-btn mui-btn-red">删除</a></div>'+
			'<div class="mui-slider-handle"></div><div class="oneFile" data-url="'+imgURL+'">'+fileStr+'</div>';
		li.setAttribute('data-url','')
		fileUL.appendChild(li)
		imageArr.push(currFile)
		li.querySelector('.oneFile').addEventListener('tap',fileDomTapped)
	}
	return imageArr
}

//添加图片附件
function afterSelectImageFile(ulDomId,imageArr,files){
	var fileUL = $('#'+ulDomId)[0]
	var group = 1
	if (ulDomId!="fileUL") {
		group = 2
	}
	for (var i = 0; i < files.length; i++) {
		var URL = window.URL || window.webkitURL;
		var currFile = files[i]
		var imgURL = URL.createObjectURL(currFile);
		var li = document.createElement('li');
		li.classList.add('mui-table-view-cell')
		li.setAttribute('data-url','')
		li.id = ulDomId + '-' + imageArr.length
		li.innerHTML = '<img class="" data-preview-group="'+group+'" data-preview-src="" src="'+imgURL+'"/><div class="mui-icon mui-icon-closeempty"></div>'
		fileUL.appendChild(li)
		imageArr.push(currFile)
	}
	return imageArr
}

//新建页面文件列表渲染
function updateFileUI(keyStr,fileUlId,dataDict,rw,path){
	var fileUrl = dataDict[keyStr]||""
	var arr = fileUrl.split('」') //ActivityFile  StandardFile
	var html = ''
	for (var i= 0; i < arr.length;i++) {
		var fileUrl = arr[i]
		if (fileUrl=="") {
			continue
		}
		var delUrl=fileUrl
		if (path&&fileUrl.indexOf('Fileupdate/images/')==-1) {
			fileUrl = 'Fileupdate/images/'+path+'/'+rw+'/'+fileUrl
		}
		var index = fileUrl.lastIndexOf("\/");
		fileName=fileUrl.substring(index+1,fileUrl.length);
		var icon = fileTypeIcon(fileName);
		var fileStr = ''
		//console.log(icon)
		if (icon == 'img') {
			icon = TomcatUrl +'/' + fileUrl +'" data-preview-group="1" data-preview-src="'
		}else{
			icon = '../../dependence/teach/images/'+icon+'.svg'
		}
		fileStr = '<div class="itemImg"><img src="'+icon+'"/></div><div class="mui-ellipsis itemText">'+fileName+'</div>'
		
		html += '<li data-url="'+fileUrl+'" data-del="'+delUrl+'" class="mui-table-view-cell" data-rw="'+rw+'">'+
			'<div class="mui-slider-right mui-disabled"><a class="mui-btn mui-btn-red">删除</a></div>'+
			'<div class="mui-slider-handle"></div><div class="oneFile" data-url="'+TomcatUrl +'/' + fileUrl+'">'+fileStr+'</div></li>'
	}
	mui('#'+fileUlId)[0].innerHTML = html
	mui('#'+fileUlId +' .oneFile').each(function (index,element) {
		element.addEventListener('tap',fileDomTapped)
	})
}
//新建页面文件列表渲染
function updateImageFileUI(keyStr,fileUlId,dataDict,rw,path){
	var fileStr = dataDict[keyStr]||""
	var arr = fileStr.split('」') //ActivityFile  StandardFile
	var html = ''
	var group = 1
	if (fileUlId != 'fileUL') {
		group = 2
	}
	for (var i= 0; i < arr.length;i++) {
		var fileUrl = arr[i]
		if (fileUrl=="") {
			continue
		}
		var delUrl=fileUrl
		console.log(fileUrl)
		if (path&&fileUrl.indexOf('Fileupdate/images/')==-1) {
			fileUrl = 'Fileupdate/images/'+path+'/'+rw+'/'+fileUrl
		}
		html += '<li data-url="'+fileUrl+'" data-del="'+delUrl+'" class="mui-table-view-cell" data-rw="'+rw+'">'+
			'<img class="" data-preview-group="'+group+'" data-preview-src="" src="'+TomcatUrl +'/' + fileUrl+'"/>'+
			'<div class="mui-icon mui-icon-closeempty"></div></li>'
	}
	mui('#'+fileUlId)[0].innerHTML = html
}

//点击文件删除
function deleteFileBtnTapped(btnDom,paramDict,resultBlock){ //文件删除
	var imgArr = paramDict.imgArr
	var li = btnDom.parentNode
	if (btnDom.getAttribute('class').indexOf('mui-icon') == -1) {
		li = li.parentNode
	}
	var ulDom = li.parentNode
	var liId=ulDom.id
	var filepath = li.getAttribute('data-url')
	if (filepath == '') {
		var index = li.id.replace(liId+'-','')
		imgArr.splice(index,1)
		ulDom.removeChild(li)
		mui('#'+liId+' li[data-url=""]').each(function (newIndex,element) {
			element.id = liId+'-'+newIndex
		})
		resultBlock(true,imgArr)
		return
	}
	//删除文件
	var delpath = li.getAttribute('data-del')
	mui.DeleteFileFromServer(filepath,function(flag){
		if (!flag) {
			resultBlock(false)
			return
		}
		deleteFileParam(delpath,li,paramDict,function(flag){
			resultBlock(flag)
		})
	})
}

//删除文件参数
function deleteFileParam(name,dom,paramDict,resultBlock){ 
	var id = dom.getAttribute('data-rw')
	var self = plus.webview.currentWebview()
	var method = paramDict.method
	var pdict = {'id':id,'name':name,'nurseid':paramDict.nurseid}
	if (paramDict['otherParams']) {
		pdict['parr'] = id+paramDict['otherParams']+name
	}
	console.log(method +' '+JSON.stringify(pdict))
	var paramDict = {'method':method,'params':JSON.stringify(pdict),'type':'Method'}
	mui.DHCWebService(paramDict, function(result) {
		//console.log(JSON.stringify(result))
		var msg = parseInt(result['msg'])
		if (msg == 0) {
			mui.toast('文件删除失败')
			resultBlock(false)
			return 
		}
		resultBlock(true)
		dom.parentNode.removeChild(dom)
		var listPageId = '../WKPlatformPages/ky/keyanList.html'
		if (self.id == 'zkNew') {
			listPageId = '../WKPlatformPages/zk/zkList.html'
		}else if ('criticPraiseNew,dutyNew,registedResignNew'.indexOf(self.id)!= -1) {
			listPageId = '../WKPlatformPages/apply/applyList.html'
		}
		var webview = plus.webview.getWebviewById(listPageId)
		if (webview) {
			webview.evalJS('detailChanged()')
		}
		
	}, function(errorStr) {
		mui.toast('请重试')
	});
}

function saveFileAction(paramDict,resultBlock){
	plus.nativeUI.showWaiting('正在上传文件')
	if (paramDict.imgArr.length == 0) {
		plus.nativeUI.closeWaiting()
		resultBlock(true)
		return
	}
	var id = paramDict.id
	mui.UploadFileToServer(paramDict.imgArr,paramDict.path+'/'+id,function(shortArr){
		if (!shortArr) {
			plus.nativeUI.closeWaiting()
			resultBlock(false)
			return
		}
		saveFileParam(id,shortArr,paramDict.method,paramDict['otherParams'],paramDict.spStr,function(flag){
			resultBlock(flag)
		});
	})
}
function saveFileParam(id,shortArr,method,otherParams,spStr,resultBlock){
	var name = shortArr.join('」') //多个之间」分隔
	var pdict = {'id':id,'name':name}
	 if (otherParams) {
		pdict['parr'] = otherParams+shortArr.join('」')
		if (spStr) {
			pdict['parr'] = otherParams+shortArr.join(spStr)
		}
	 }else{
		mui.each(shortArr,function (index,url) {
			var arr = url.split('/')
			shortArr[index]=arr[arr.length - 1]
		})
		pdict.name = shortArr.join('」')
	 }
	//console.log(JSON.stringify(pdict)+ ' '+method)
	var paramDict = {'method':method,'params':JSON.stringify(pdict),'type':'Method'}
	mui.DHCWebService(paramDict, function(result) {
		plus.nativeUI.closeWaiting()
		//console.log(JSON.stringify(result))
		var msg = parseInt(result['msg'])
		if (msg == 0) {
			resultBlock(false)
			mui.toast('文件保存失败')
			return 
		}
		resultBlock(true)
	}, function(errorStr) {
		mui.toast('请重试')
		plus.nativeUI.closeWaiting()
	});
}

//文件保存接口
function getSaveFileMethod(type){
	var method = ''
	switch (type){
		case '发表论文备案':
			method = 'web.INMSMComm:SaveThesisFile'
			break;
		case '获奖论文备案':
			method = 'web.INMSMComm:SaveAwardFile'
			break;
		case '上交论文备案':
			method = 'web.INMSMComm:SaveEndFile'
			break;
		case '科室创新备案':
			method = 'web.INMSMComm:SaveLocInnBfPic' //web.INMSMComm:SaveLocInnAfPic
			break;
		case '获奖创新备案':
			method = 'web.INMSMComm:SaveAwa'
			break;
		case '专利备案':
			method = 'web.INMSMComm:SavePatentPic'
			break;
		case '专科活动备案':
			method = 'web.INMSpecialComm:SaveActivityFile'
			break;
		case '规范参与备案':
			method = 'web.INMSpecialComm:SaveStandardFile'
			break;
		default:
			break;
	}
	return method
}
//文件删除接口
function getDeleteFileMethod(type){
	var method = ''
	switch (type){
		case '发表论文备案':
			method = 'web.INMSMComm:DeleteThesisFile'
			break;
		case '获奖论文备案':
			method = 'web.INMSMComm:DeleteAwardFile'
			break;
		case '上交论文备案':
			method = 'web.INMSMComm:DeleteEndFile'
			break;
		case '科室创新备案':
			method = 'web.INMSMComm:DeleteLocInnBfPic'  //web.INMSMComm:DeleteLocInnAfPic
			break;
		case '获奖创新备案':
			method = 'web.INMSMComm:DeleteAwa'
			break;
		case '专利备案':
			method = 'web.INMSMComm:DeletePatentPic'
			break;
		case '专科活动备案':
			method = 'web.INMSpecialComm:DeleteActivityFile'
			break;
		case '规范参与备案':
			method = 'web.INMSpecialComm:DeleteStandardFile'
			break;
		default:
			break;
	}
	return method
}
//
function getUploadFileToServerPath(type){
	var method = ''
	switch (type){
		case '发表论文备案':
			method = 'Thesis'
			break;
		case '获奖论文备案':
			method = 'Award'
			break;
		case '上交论文备案':
			method = 'EndYearThesis'
			break;
		case '科室创新备案':
			method = 'LocInn'
			break;
		case '获奖创新备案':
			method = 'AwaInn'
			break;
		case '专利备案':
			method = 'Patent'
			break;
		case '专科活动备案':
			method = 'SpecialActivity'
			break;
		case '规范参与备案':
			method = 'StandardParticipation'
			break;
		default:
			break;
	}
	return method
}
function fileTypeIcon(url){
	var icon = ''
	url = url.toLowerCase()
	if (url.endsWith(".pdf")) {
		icon = 'pdf'
	}else if (url.endsWith(".png")||url.endsWith(".jpg")||url.endsWith(".jpeg")||url.endsWith(".gif")||url.endsWith(".bmp")) {
		icon = 'img'
	}else if (url.endsWith(".doc") || url.endsWith(".docx")) {
		icon = 'word'
	}else if (url.endsWith(".ppt") || url.endsWith(".pptx")) {
		icon = 'ppt'
	}else if (url.endsWith(".txt") || url.endsWith(".json")) {
		icon = 'txt'
	}else{
		icon = 'file'
	}
	return icon
}